#!/usr/bin/python
from uya.configmod_web import html_helpers as hh

def flatten(lstlst):
    return [x for lst in lstlst for x in lst]

def combinations(items, n):
    if n == 0: 
        yield []
    else:
        for i in xrange(len(items)):
            for cc in combinations(items[i+1:], n-1):
                yield [items[i]] + cc

def get_option(text, value, current_value):
    if value == current_value:
        return '<option value="%s" selected="selected">%s</option>' % (value, text)
    return '<option value="%s">%s</option>' % (value, text)

def get_interfaces(config, itypes):
    def enabled(itype):
        return [iface for iface in config["interfaces"][itype]
            if config["interfaces"][itype][iface]["state"]]
    return list(sorted(flatten(enabled(itype) for itype in itypes)))    

def get_bridge_ports_html(config, name, value):
    interfaces = list(sorted(config["interfaces"]["ethernet"]))        
    options = [get_option("%s <-> %s" % (iface1, iface2),
        "%s %s" % (iface1, iface2), value) for 
        (iface1, iface2) in combinations(interfaces, 2)]
    html_options = get_option("Disabled", "", None) + "".join(options)
    return '<select name="%s">%s</select>' % (name, html_options)

def get_default_nat_html(config, name, value):
    interfaces = get_interfaces(config, ["ethernet", "wireless", "bridging"])        
    options = get_option("Disabled", "", None) + \
        "".join([get_option(s, s, value) for s in interfaces])
    return '<select name="%s">%s</select>' % (name, options)

def get_dynamic_interfaces_html(config, name, value):
    interfaces = get_interfaces(config, ["ethernet", "wireless", "bridging"])
    if not interfaces:
        return "<i>No ethernet or wireless interfaces enabled</i>"
    def get_checkbox(s):
        if s in value:
            return hh.input_tag('checkbox', name, value=s, checked="checked") + s
        else: return hh.input_tag('checkbox', name, value=s) + s
    inputs = [get_checkbox(s) for s in interfaces]
    return hh.input_tag('hidden', name, value='') + "".join(inputs)
